import { BaseContext } from "koa";
import { getRepository } from "typeorm";
import authorize from "../../middleware/authorize";
import { Get, Post, Controller } from "../../middleware/request";
import { Exception } from "../../utils/exception";
// import { User } from "../entity/User";
import { auth as Auth } from "../../utils/auth";
import { createTimestamp, createNonceStr } from "../../utils/index";
import { WX_CLIENT } from "../../config";
const sha1 = require('sha1');
const axios = require('axios')
@Controller("/api")
export class wxController {
	//   @authorize()
	@Get("/getUserInfo")
	async getUserInfo(ctx: BaseContext) {
		const { code } = ctx.request.query;
		try {
			let user = await oauthUser(code)
			ctx.body = {
				...Exception(200, "获取成功"),
				data: user
			};
		} catch (error) {
			ctx.body = {
				...Exception(112, "获取失败"),
				data: error,
			};
		}
	}

	@Get('/getCode')
	async getCode(ctx: BaseContext) {
		const { url = 'http://10.147.18.191:8080' } = ctx.request.query;
		let code_url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WX_CLIENT.appId}&redirect_uri=${encodeURIComponent(url)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
		ctx.body = {
			...Exception(200, "获取成功"),
			data: code_url
		}
	}

	@Get("/wxShare")
	async getWxShare(ctx: BaseContext) {
		let { url } = ctx.request.query;
		try {
			const shareConfig = await getSign(url);
			const shareInfo = {
				title: "分享标题",
				desc: "分享文本内容",
				link: "链接",
				img: ''
			}
			let data = {
				config: shareConfig,
				info: shareInfo
			}
			ctx.body = {
				...Exception(200, "获取成功"),
				data: data
			}
		} catch (error) {
			ctx.body = {
				...Exception(112, "获取失败"),
				data: error,
			};
		}
	}
}
/**
 * code
 *  通过code换取网页授权access_token
 */
async function oauthAccessToken(code: string) {
	let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WX_CLIENT.appId}&secret=${WX_CLIENT.appsecret}&code=${code}&grant_type=authorization_code`
	let res = await axios.get(url)
	return res.data
}

/**
 * code
 * 获取用户信息
 */
async function oauthUser(code: string) {
	try {
		let accessToken = await oauthAccessToken(code)
		let url = `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken.access_token}&openid=${accessToken.openid}&lang=zh_CN`
		let res = await axios.get(url)
		console.log('res', res);

		return res.data
	} catch (error) {
		return error
	}
}

/**
 * 获取access_Ttoken
 */
async function getAccessToken() {
	const api = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${WX_CLIENT.appId}&secret=${WX_CLIENT.appsecret}`;
	try {
		const { data } = await axios.get(api);
		if (data.access_token) {
			return data.access_token
		}
		return Promise.reject(data)
	} catch (error) {
		return Promise.reject(error)
	}
}
/**
 * 获取Jsapi_Ticket
 */
async function getTicket() {
	try {
		const access_token = await getAccessToken()
		const api = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
		const { data } = await axios.get(api)
		if (data.ticket) {
			return data.ticket
		}
		return Promise.reject(data)
	} catch (error) {
		return Promise.reject(error)
	}
}

/**
 * 获取签名
 */
async function getSign(url = '') {
	try {
		const ticket = await getTicket();
		const timestamp = createTimestamp();
		const nonceStr = createNonceStr();
		// 参数的顺序要按照 key 值 ASCII 码升序排序
		const string = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
		const signature = sha1(string)
		let data = {
			appId: WX_CLIENT.appId,
			nonceStr,
			timestamp,
			url,
			signature,
			rawString: string
		}
		return data
	} catch (error) {
		return Promise.reject(error)
	}
}